package com.teatrace.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ServiceContext {

	private static final Logger logger = Logger.getLogger(ServiceContext.class);

	private static final String propertyFile = "services.properties";

	private static Properties pro = new Properties();

	private static Map<String, Object> serviceMapping = new HashMap<String, Object>();

	private static boolean singleton = false;

	static {
		try {
			pro.load(ServiceContext.class.getClassLoader().getResourceAsStream(
					propertyFile));
			singleton = new Boolean(pro.getProperty("singleton"));
		} catch (IOException e) {
			logger.error(e);
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T getService(Class<T> clazz) {
		if (singleton) {
			Object service = null;
			service = serviceMapping.get(clazz.getName());
			if(service == null) {
				service = createService(clazz);
				serviceMapping.put(clazz.getName(), service);
			}
			return (T) service;
		} else {
			return (T) createService(clazz);
		}
		
	}

	private static Object createService(Class clazz) {
		try {
			return Class.forName(pro.getProperty(clazz.getSimpleName()))
					.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("Can't new a service intance : "
					+ clazz.getName());
		}
	}
}
